<?php
/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/11
 * Time: 17:05
 */

namespace app\api\controller;


use app\api\Base2Controller;
use think\Db;

/**
 * 服务端资料库
 * Class Tonggao
 * @package app\api\controller
 */
// extends Base2Controller
class Tonggao extends Base2Controller
{
    /**
     * 通告列表
     */
    public function tonggaoList()
    {
        $time = time();
        $page = intval(input('page'))?intval(input('page')):1;
        $pagesize = intval(input('pagesize'))?intval(input('pagesize')):15;
        $typeid = intval(input('typeid'))?1:0;
        $where=[];
        if ($typeid){
            $where['typeid']=$typeid;
        }
        $offset = ($page-1)*$pagesize;
        #当前大于等于开始时间,当前时间小于等于结果时间
        $result = Db::name('affiches')
            ->where('start_time','<=',$time)
            ->where('end_time','>=',$time)
            ->where($where)
            ->order('sort desc')
            ->limit($offset,$pagesize)
            ->field('affiche_id,title,updated_at')
            ->select();

        $user_id = $this->user_id;
        foreach ($result as $key => $value) {
            $read_info = db('affiche_reads')->where(['affiche_id'=>$value['affiche_id'],'member_id'=>$user_id])->select();
            if(!empty($read_info)){
                $result[$key]['read_status'] = 1; #已读
            }else{
                $result[$key]['read_status'] = 0; #未读
            }
        }    
        return json_success_return($result);
    }

    /**
     * 通告详情
     */
    public function tonggaodetail()
    {
        $time= time();
        if (empty($id = intval(input('detailid'))))
        {
            return json_fail_return('请正确输入信息');
        }
        $where['affiche_id'] = $id;
        $result = Db::name('affiches')
            ->where('start_time','<=',$time)
            ->where('end_time','>=',$time)
            ->where($where)
            ->field('affiche_id,title,contents,updated_at')
            ->select();

        #判断已读未读
        $user_id = $this->user_id;

        $read_info = db('affiche_reads')->where(['affiche_id'=>$id,'member_id'=>$user_id])->select();
        $affiche_info = db('affiches')->where(['affiche_id'=>$id])->find();

        if(empty($read_info)){
            $data = [
                'member_id'=>$user_id,
                'affiche_id' => $id,
                'created_at' => time()
            ];
            db('affiche_reads')->insertGetId($data);

            $new['already_read'] = $affiche_info['already_read'] + 1;
            $new['unread'] = $affiche_info['unread'] - 1;
            db('affiches')->where(['affiche_id'=>$id])->update($new);
        }
            
        return json_success_return($result);
    }


}
